package com.innovation.ic.sc.web.schedule;

import com.alibaba.fastjson.JSONObject;
import com.innovation.ic.sc.base.model.erp9_pvebcs.CompanyCurrency;
import com.innovation.ic.sc.base.model.sc.MyCompanyCurrency;
import com.innovation.ic.sc.web.controller.sc_data.InitClientController;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 同步erp,我的公司币种信息
 */
@Component
public class importCompanyCurrencyJobSchedule extends AbstractSchedule {
    private static final Logger log = LoggerFactory.getLogger(InitClientController.class);

    @XxlJob("importCompanyCurrencyJob")
    private void importCompanyCurrencyJob() {
        try {
            String jobParam = XxlJobHelper.getJobParam();
            XxlJobHelper.log("拿到执行器参数 {} ", jobParam);
            List<String> nameList = new ArrayList<>();
            nameList.add("人民币");
            nameList.add("美元");
            List<CompanyCurrency> companyCurrencys = super.companyCurrencyService.findCompanyCurrency(nameList);
            if (CollectionUtils.isEmpty(companyCurrencys)) {
                return;
            }
            log.info("importCompanyCurrencyJob 拿到erp得返回结果 : {}", JSONObject.toJSONString(companyCurrencys));
            super.myCompanyCurrencyService. truncate();
            super.myCompanyCurrencyService.saveBatch(this.bindMyCompanyCurrency(companyCurrencys));
            XxlJobHelper.handleSuccess();
        } catch (Exception e) {
            log.error("同步erp我的公司币种错误", e);
            XxlJobHelper.handleFail();
        }
    }


    /**
     * 绑定参数
     *
     * @param companyCurrencys
     * @return
     */
    public List<MyCompanyCurrency> bindMyCompanyCurrency(List<CompanyCurrency> companyCurrencys) {
        List<MyCompanyCurrency> result = new ArrayList<>();
        for (CompanyCurrency companyCurrency : companyCurrencys) {
            MyCompanyCurrency myCompanyCurrency = new MyCompanyCurrency();
            myCompanyCurrency.setName(companyCurrency.getName());
            myCompanyCurrency.setEnName(companyCurrency.getEnName());
            myCompanyCurrency.setSymbol(companyCurrency.getSymbol());
            myCompanyCurrency.setShortSymbol(companyCurrency.getShortSymbol());
            myCompanyCurrency.setCumericCode(companyCurrency.getCnumericCode());
            myCompanyCurrency.setOrderIndex(companyCurrency.getOrderIndex());
            myCompanyCurrency.setExternalId(companyCurrency.getExternalId());
            myCompanyCurrency.setCreateDate(new Date());
            result.add(myCompanyCurrency);
        }
        return result;
    }
}